package Tables;

/*
 * SimpleTableDemo.java requires no other files.
 */
 
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import TableAdditions.PersonelAddition;
import Utility.Product;
import TableAdditions.ProductAddition;
import TableAdditions.main;
import TableEditions.ProductEdition;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class ProductTableInterface extends JPanel implements ActionListener  {
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    JButton productAddButton=new JButton("Yeni");
    JButton productDeleteButton=new JButton("Sil");
    JButton productEditButton=new JButton("Düzenle");
    ProductAddition additive;
    ProductEdition edit;
    Product[] products;
    final String[] newData=new String[9]; 
    int selectedRow=-1;
    
    public ProductTableInterface() {
    	
    	//super(new GridBagLayout());
 
        String[] columnNames = {"Ürün Kodu",
                                "Ürün Adı",
                                "Satici",
                                "Alis Fiyatı",
                                "Satış Fiyatı"};
        
       /* TableColumn column = new TableColumn();
        for (int i = 0; i < columnNames.length; i++) {
            column = table.getColumnModel().getColumn(i);
            if (i == 0) {
                column.setPreferredWidth(11); //third column is bigger
            }
            else if (i==1){
            	column.setPreferredWidth(10);
            }
            else {
                column.setPreferredWidth(45);
            }
        }*/
 
       

        for(int i=0;i<columnNames.length;i++)
        	model.addColumn(columnNames[i]);	//add columns
        
        
      
        addNewItem();
       
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
      //Add the scroll pane to this panel.
        add(scrollPane);
        
        
        table.addMouseListener(new MouseAdapter() {
			
			
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				 if (table.getColumnSelectionAllowed()
		                    && !table.getRowSelectionAllowed()) {
					  
		                System.out.println("11111111111111");
		                // Column selection is enabled
		                // Get the indices of the selected columns
		                int[] vColIndices = table.getSelectedColumns();
		            } else if (!table.getColumnSelectionAllowed()
		                    && table.getRowSelectionAllowed()) {
		            	// System.out.println("222222222222");
		            	 selectedRow=table.getSelectedRow(); 
		            	 
		            	 //System.out.println("selectedCustomer= "+customerNames[selectedRow]);
		                // Row selection is enabled
		                // Get the indices of the selected rows
		                int[] rowIndices = table.getSelectedRows();
		            } else if (table.getCellSelectionEnabled()) {
		                // Individual cell selection is enabled
		            	System.out.println("333333333333");

		                // In SINGLE_SELECTION mode, the selected cell can be retrieved using
		            	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		                int rowIndex = table.getSelectedRow();
		                int colIndex = table.getSelectedColumn();
		              

		                // In the other modes, the set of selected cells can be retrieved using
		                table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		                // Get the min and max ranges of selected cells
		                int rowIndexStart = table.getSelectedRow();
		                int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
		                int colIndexStart = table.getSelectedColumn();
		                int colIndexEnd = table.getColumnModel().getSelectionModel()
		                    .getMaxSelectionIndex();

		                // Check each cell in the range
		                for (int r=rowIndexStart; r<=rowIndexEnd; r++) {
		                    for (int c=colIndexStart; c<=colIndexEnd; c++) {
		                        if (table.isCellSelected(r, c)) {
		                        	System.out.println("4444444444444");
		                            // cell is selected
		                        }
		                    }
		                }
		            }
				
			}
		});
        
        
        productAddButton.addActionListener(this);
        
        productAddButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				additive=new ProductAddition(ProductTableInterface.this);

				
			}
			
			
		});
        
        productEditButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				if(selectedRow>-1){
					edit=new ProductEdition(ProductTableInterface.this,products[selectedRow]);
				}

				
			}
			
			
		});
        
        productDeleteButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(selectedRow!=-1){
					System.out.println("Delete special price");
					
					Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";
			        Object[][] mydata=null;
			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate("UPDATE product set activity='0' WHERE product_id='"+products[selectedRow].getProductId()+"'");
			            st.executeUpdate("DELETE from special_price WHERE special_price_product_id='"+products[selectedRow].getProductId()+"'");
			            addNewItem();
			           
			            
			            con.close();
			            
			            
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
					/////////////////////////////////////////
				}
				
				

				
			}
			
			
		});
        
        
        addItem(productAddButton,0,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(productDeleteButton,1,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(productEditButton,2,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        
        
       
       
    }
    
    /**
     * This method Add new row to the table
     */
    private void addTableByRow(Object[] yeni){
    	model.addRow(yeni);
   }
 
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    public void createAndShowGUI() {
        //Create and set up the window.
        JFrame myframe = new JFrame("Ürün Tablosu");
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Create and set up the content pane.
        ProductTableInterface newContentPane = new ProductTableInterface();
        newContentPane.setOpaque(true); //content panes must be opaque
        myframe.setContentPane(newContentPane);
 
        //Display the window.
        TableGetXY tmp=new TableGetXY();
        myframe.setLocation(tmp.upperLeftX,tmp.upperLeftY);
        myframe.pack();
        myframe.setVisible(true);
    }

    /**
     *This method is good to use GridBagLayout simple
     * 
     */
    private void addItem(JComponent c, int x, int y, int width, int height, int align) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = x;
        gc.gridy = y;
        gc.gridwidth = width;
        gc.gridheight = height;
        gc.weightx = 100.0;
        gc.weighty = 100.0;
        gc.insets = new Insets(5, 5, 5, 5);
        gc.anchor = align;
        gc.fill = GridBagConstraints.NONE;
        add(c, gc);
      }
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void addNewItem() {
		deleteAllRows(model);	
		
		  table.setPreferredScrollableViewportSize(new Dimension(920, 600));
	        table.setFillsViewportHeight(true);
	       
	      
	       
	        
	        Connection con = null;
	        Statement st = null;
	        ResultSet rs = null;

	        String url = "jdbc:mysql://localhost:3306/mydb";			/////connection setups
	        String user = "root";
	        String password = "qweasdzxc";
	        Object[][] mydata=null;
	        int counter=0;
	        try {
	            con = (Connection) DriverManager.getConnection(url, user, password);		//create connections and setups
	            st = (Statement) con.createStatement();
	            rs=st.executeQuery("SELECT * from product WHERE activity='1' ORDER BY product_name ");		//get query to the rs
	            int i=0;
	            while(rs.next())
	            	++counter;
	            if(counter!=0){
	            rs.first();
	            products = new Product[counter];
	            products[i]=new Product();
	            mydata=new Object[counter][5];
	            products[i].setProductId(rs.getInt("product_id"));
	            mydata[i][0]=rs.getString("product_code");							
	            products[i].setProductCode(rs.getString("product_code"));
	            mydata[i][1]=rs.getString("product_name");
	            products[i].setProductName(rs.getString("product_name"));
	    		mydata[i][2]=rs.getString("product_supplier_code");
	    		products[i].setProductSupplierCode(rs.getString("product_supplier_code"));
	    		mydata[i][3]=rs.getFloat("product_buying_price");
	    		products[i].setProductBuyingPrice(rs.getFloat("product_buying_price"));
	    		mydata[i][4]=rs.getFloat("product_selling_price");
	    		products[i].setProductSellingPrice(rs.getFloat("product_selling_price"));
	    		++i;
	    		
	            while(rs.next())								
	            {
	            	products[i]=new Product();
	 	            products[i].setProductId(rs.getInt("product_id"));
	 	            mydata[i][0]=rs.getString("product_code");							
	 	            products[i].setProductCode(rs.getString("product_code"));
	 	            mydata[i][1]=rs.getString("product_name");
	 	            products[i].setProductName(rs.getString("product_name"));
	 	    		mydata[i][2]=rs.getString("product_supplier_code");
	 	    		products[i].setProductSupplierCode(rs.getString("product_supplier_code"));
	 	    		mydata[i][3]=rs.getFloat("product_buying_price");
	 	    		products[i].setProductBuyingPrice(rs.getFloat("product_buying_price"));
	 	    		mydata[i][4]=rs.getFloat("product_selling_price");
	 	    		products[i].setProductSellingPrice(rs.getFloat("product_selling_price"));
	 	    		++i;
	            }
	            
	            
	            }
	            con.close();
	        } catch (SQLException ex) {
	            Logger lgr = Logger.getLogger(main.class.getName());
	            lgr.log(Level.SEVERE, ex.getMessage(), ex);

	        } finally {
	            try {
	                if (rs != null) {
	                    rs.close();
	                }
	                if (st != null) {
	                    st.close();
	                }
	                if (con != null) {
	                    con.close();
	                }

	            } catch (SQLException ex) {
	                Logger lgr = Logger.getLogger(main.class.getName());
	                lgr.log(Level.WARNING, ex.getMessage(), ex);
	            }
	        }
		
	        if(counter!=0)
	        	for(int i=0;i<mydata.length;i++)
	        		model.addRow(mydata[i]);
	  
	    
	        
		
	}
	
	 public static void deleteAllRows(final DefaultTableModel model) {
		    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
		        model.removeRow(i);
		    }
		}
}

